package com.scs.application.modules.base.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.modules.base.entity.Certificate;
import com.scs.application.modules.base.entity.Matr;
import com.scs.application.modules.base.mapper.CertificateMapper;
import com.scs.application.modules.base.mapper.MatrMapper;
import com.scs.application.modules.base.service.CertificateService;
import com.scs.application.modules.base.util.CommonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 资质预警表 服务实现类
 * </p>
 */
@Service
public class CertificateServiceImpl extends BaseServiceImpl<CertificateMapper, Certificate> implements CertificateService {
    @Autowired
    MatrMapper matrMapper;
    public static final Logger logger = LoggerFactory.getLogger(CertificateServiceImpl.class);
    @Override
    public void autoEarlyWarning() {
        //1.先拿到所有没有到期之前正常的资质数据
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String dayStr = sf.format(new Date());
        String today = dayStr + " 23:59:59";
        Date todayDate;
        List<String> msgs = new ArrayList();
        try {
            todayDate = DateUtils.parse(today,"yyyy-MM-dd HH:mm:ss");
            List<Certificate> allCertificates = this.list(Wrappers.<Certificate>query().ge("expiry_date", today).eq("close_flag","0"));
            List<Certificate> warningCertificates = allCertificates.stream().filter(certificate -> {
                boolean b = DateUtils.addDays(todayDate, certificate.getEarlyWarningDays() + 1).compareTo(certificate.getExpiryDate()) >= 0;//今天+预警天数超过到期日+1天 如果大于等于 到期日
                return b;
            }).collect(Collectors.toList());
            ArrayList<Certificate> expiredCertificates = new ArrayList();
            warningCertificates.stream().forEach(c->{
                try {
                    long days = (DateUtils.parse(sf.format(c.getExpiryDate()), "yyyy-MM-dd").getTime()-DateUtils.parse(dayStr, "yyyy-MM-dd").getTime())/(24*60*60*1000);
                    if (days == -1) {//等于-1的就是昨天是效期的最后一天，今天过效期，就要在今天凌晨跑批时去禁用对应所有耗材（一般都要放在凌晨几点钟去跑，最迟要放在白天上班之前跑）
                        expiredCertificates.add(c);
                    }
                    String content = c.getTargetName() + " " + c.getCertificateName() + " " + c.getCertificateCode() + "将于 " + sf.format(c.getExpiryDate()) + " 到期距今天还有 " + days + "天";
                    msgs.add(content);
                    CommonService.pushMessageRole("资质效期提醒:", content, "admin,admin_yy", DateUtils.format(new Date(), "yyMMddHHmmss") + c.getId());
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            });
            if (!CollectionUtils.isEmpty(expiredCertificates)) {
                for (Certificate certificate : expiredCertificates) {//把已经到期的资质对应的所有耗材都设置为禁用状态
                    updateMatrForbiddenByCertificate(certificate, 1);
                }
            }

        } catch (ParseException e) {
            e.printStackTrace();
            logger.error("autoEarlyWarning,{}",e);
        }

    }
    @Override
    public void updateMatrForbiddenByCertificate(Certificate certificate, int forbiddenFlag) {
        if (certificate.getTargetFlag() == 0) {//资质归属标志 0-供应商
            if (forbiddenFlag == 1) {//1-禁用 0-不禁用
                matrMapper.update(null,Wrappers.<Matr>update()
                        .eq("supplier_id",certificate.getTargetId())
                        .set("flag_forbidden",forbiddenFlag)
                        .set("forbidden_type_sur",certificate.getCertificateType() + "")
                        .set("gmt_modified",new Date()));
            } else {//取消禁用
                //把厂商的已经没有过期的耗材取消禁用
                matrMapper.update(null,Wrappers.<Matr>update()
                        .eq("supplier_id",certificate.getTargetId()).eq("forbidden_type_mfg", "0")
                        .set("flag_forbidden",forbiddenFlag)
                        .set("forbidden_type_sur", "0")
                        .set("gmt_modified",new Date()));
                //把厂商的还有过期的供应商禁用类型设置为0-没有供应商禁用
                matrMapper.update(null,Wrappers.<Matr>update()
                        .eq("supplier_id",certificate.getTargetId()).ne("forbidden_type_mfg", "0")
                        .set("flag_forbidden",1)
                        .set("forbidden_type_sur", "0")
                        .set("gmt_modified",new Date()));
            }

        } else {//1-厂商
            if (forbiddenFlag == 1) {//1-禁用 0-不禁用
                matrMapper.update(null,Wrappers.<Matr>update()
                        .eq("mfg_id",certificate.getTargetId())
                        .set("flag_forbidden",forbiddenFlag)
                        .set("forbidden_type_mfg",certificate.getCertificateType() + "")
                        .set("gmt_modified",new Date()));
            } else {//取消禁用
                //把供应商的已经没有过期的耗材取消禁用
                matrMapper.update(null,Wrappers.<Matr>update()
                        .eq("mfg_id",certificate.getTargetId()).eq("forbidden_type_sur", "0")
                        .set("flag_forbidden",forbiddenFlag)
                        .set("forbidden_type_mfg", "0")
                        .set("gmt_modified",new Date()));
                //把供应商的还有过期的供应商禁用类型设置为0-没有供应商禁用
                matrMapper.update(null,Wrappers.<Matr>update()
                        .eq("mfg_id",certificate.getTargetId()).ne("forbidden_type_sur", "0")
                        .set("flag_forbidden",1)
                        .set("forbidden_type_mfg", "0")
                        .set("gmt_modified",new Date()));
            }


        }
    }
}
